import { ToastAndroid } from 'react-native';

import CommonUtils from './common';
import GlobalConfig from './Global';

/**
 * 本地校验是否符合规则
 * @param {用户名} userName 
 * @param {密码} password 
 */
const validation = (userName, password) => {
    if (CommonUtils.isBlank(userName)) {
        ToastAndroid.show("用户名为空", ToastAndroid.SHORT);
        return false;
    }

    if (CommonUtils.isBlank(password)) {
        ToastAndroid.show("密码为空", ToastAndroid.SHORT);
        return false;
    }

    // if (password.length < 6) {
    //     ToastAndroid.show("密码不足6位", ToastAndroid.SHORT);
    //     return false;
    // }

    return true;
}

/**
 * 登录
 * 本地校验信息，成功后发起远程调用
 * @param {用户名} userName
 * @param {密码} password
 * @param {导航} navigate
 * @param {用户名引用} userNameRef
 * @param {密码引用} passwordRef
 */
exports.sign = (userName, password, navigate, userNameRef, passwordRef) => {
    if (!validation(userName, password)) {
        return false;
    }

    userNameRef.blur();
    passwordRef.blur();
    
    let option = "name=" + userName + "&pwd=" + password;
    return CommonUtils.requestUrl(GlobalConfig.LOGIN_REQUEST_URL, option, (responseText) => {
        let result = JSON.parse(responseText);
        if (result) {
            if (result.code == 12000) {
                navigate('StatusCheck');
            } else {
                ToastAndroid.show(result.msg, ToastAndroid.SHORT);
            }
        }
    }, () => {
        ToastAndroid.show("网络请求失败", ToastAndroid.SHORT);
    });

}


/**
 * 本地网关登录
 * 本地校验信息，成功后发起远程调用
 * @param {用户名} userName
 * @param {密码} password
 * @param {导航} navigate
 * @param {用户名引用} userNameRef
 * @param {密码引用} passwordRef
 */
exports.localGatewaySign = (userName, password, navigate, userNameRef, passwordRef) => {
    if (!validation(userName, password)) {
        return false;
    }

    userNameRef.blur();
    passwordRef.blur();

    // remoteValidation(GlobalConfig.LOCAL_GATEWAYLOGIN_REQUEST_URL, userName, password);
    if (userName == 'admin' && password == '123456') {
        navigate('StatusCheck');
    } else {
        ToastAndroid.show("用户名或密码不正确", ToastAndroid.SHORT);
    }
}